﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using ProtoBuf;
using Eb;

public static class EbTool
{
    //-------------------------------------------------------------------------
    public static bool isNull(Entity et)
    {
        return (et == null || et.SignDestroy);
    }

    //-------------------------------------------------------------------------
    public static bool isNull(IComponent co)
    {
        return (co == null);
    }

    //-------------------------------------------------------------------------
    public static bool isNull(EntityMgr et_mgr)
    {
        return (et_mgr == null || et_mgr.SignDestroy);
    }

    //-------------------------------------------------------------------------
    public static byte[] protobufSerialize<T>(T obj)
    {
        byte[] data = null;
        using (MemoryStream s = new MemoryStream())
        {
            try
            {
                ProtoBuf.Serializer.Serialize<T>(s, obj);
                data = s.ToArray();
            }
            catch (Exception ex)
            {
                EbLog.Error(ex.ToString());
            }
        }
        return data;
    }

    //-------------------------------------------------------------------------
    public static T protobufDeserialize<T>(byte[] data)
    {
        T obj = default(T);
        using (MemoryStream s = new MemoryStream(data))
        {
            try
            {
                obj = ProtoBuf.Serializer.Deserialize<T>(s);

            }
            catch (Exception ex)
            {
                EbLog.Error(ex.ToString());
            }
        }

        return obj;
    }

    //-------------------------------------------------------------------------
    public static string jsonSerialize(object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

    //-------------------------------------------------------------------------
    public static T jsonDeserialize<T>(string str_json)
    {
        return (T)JsonConvert.DeserializeObject<T>(str_json);
    }

    //-------------------------------------------------------------------------
    public static byte[] bsonSerializer(object obj)
    {
        MemoryStream ms = new MemoryStream();
        using (BsonWriter writer = new BsonWriter(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(writer, obj);
            return ms.ToArray();
        }
    }

    //-------------------------------------------------------------------------
    public static T bsonDeserialize<T>(byte[] data)
    {
        MemoryStream ms = new MemoryStream(data);
        using (BsonReader reader = new BsonReader(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }
    }
}
